//
//  MYGResumeShareVC.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/4/24.
//

import UIKit
import QMUIKit

class MYGResumeShareVC: MYGBaseController {
    private var  contents:[MYGResumType] = []
    private var  mediaContents:[MYGResumType] = []

    private var  isEN:Bool = false
    private var isMedia:Bool = false
    
    private var doctorResumeModel = MYGResumeModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        confgUI()
        getResumList()
    
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func confgUI() {
        title = "我的简历"
        view.backgroundColor = .white
        view.addSubview(tableview)
        view.addSubview(shareBtn)
        shareBtn.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(bottomSafeheight)
            make.height.equalTo(49)
        }
        
        tableview.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(shareBtn.snp.top)
        }

    }

    private lazy var tableview: UITableView = {
        let tableview = UITableView(frame: CGRectZero, style: .grouped)
        tableview.delegate = self
        tableview.dataSource = self
        tableview.separatorStyle = .none
        tableview.backgroundColor = .clear
        tableview.showsVerticalScrollIndicator = false
        tableview.tableHeaderView = headerView
        tableview.register(cellWithClass: MYGResumeShareCell.self)
        tableview.register(cellWithClass: MYGResumeOtherCell.self)
        tableview.register(cellWithClass: MYGMediaTableViewCell.self)
        return tableview
    }()
    
    private lazy var headerView:MYGResumeHeaderView = {
        let header = MYGResumeHeaderView()
        header.frame = CGRectMake(0, 0, screenWidth, SCALEWIDTH(194))
        header.CNPersonInfoBlock = {[self] in
            getCNResumInfo()
        }
        header.ENPersonInfoBlock = {[self] in
            getENResumInfo()
        }
        header.mediaPersonInfoBlock = {[self] in
            getMediaResumInfo()
        }
        return header
    }()
    
    private lazy var shareBtn: QMUIButton = {
        let btn = QMUIButton()
        btn.setTitle("分享简历", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .medium(17)
        //btn.backgroundColor = .rgba(162, 146, 254, 1)
        btn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        btn.addTarget(self, action: #selector(clickShareBtn), for: .touchUpInside)
        return btn
    }()
    private lazy var tipView:MYGResumeHeaderTipview = {
        let v = MYGResumeHeaderTipview()
        return v
    }()
}
extension MYGResumeShareVC {
    
    
    @objc func clickShareBtn(){
        
        MYGLoading.show()
        
        var params:[String:Any] = [:]
        params["user_id"] = self.doctorResumeModel.doctor.id
        params["avatar"] = self.doctorResumeModel.doctor.avatar
        params["name"] = self.doctorResumeModel.doctor.name
        params["level"] = self.doctorResumeModel.doctor.level
        params["hospital"] = self.doctorResumeModel.doctor.hospital
        params["department"] = self.doctorResumeModel.doctor.department
        params["title"] = self.doctorResumeModel.doctor.title
        params["phone"] = self.doctorResumeModel.doctor.phone
        
        var indexArray:[String] = []
        self.contents.forEach { model in
            if model.isShow == 1 {
                indexArray.append(model.modelName)
            }
        }
        
        params["index"] = indexArray.joined(separator: ",")
        print(params)
        MMYGNetwork<MYGRegisterAPI,MYGEmptyModel>.request(target:.uploadDoctorInf(id:"\(self.doctorResumeModel.doctor.id)",params: params)) {[self] _ in
            MYGLoading.hide()
           
            DispatchQueue.main.async {
                let textToShare:String = "医路通"
                let imageToShare:UIImage = UIImage(named: "AppIcon")!
                let userId = MYGUserManager.getUser()?.doctor.user_id ?? 0
                let token = MYGUserManager.getUser()?.verification_token ?? ""
                let urlToShare:URL = URL(string: "\(shareUrl)/#/pages/mine/doctorResumeShare?userId=\(userId)&token=\(token)")!

                
                let activityItems:Array = [textToShare, imageToShare, urlToShare] as [Any]
                let activityVC:UIActivityViewController = UIActivityViewController.init(activityItems: activityItems, applicationActivities: nil)
                activityVC.excludedActivityTypes = [UIActivity.ActivityType.postToFacebook,UIActivity.ActivityType.airDrop]

                self.navigationController?.present(activityVC, animated: true)
            }
 
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
        
        

    }

    fileprivate func writeImageToAlbum(_ image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    }
        
    @objc fileprivate func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) {
        if let _ = error as NSError? {
            print("保存失败，请重试")
        } else {
            print("保存成功！")
        }
    }


    func getResumList() {
        self.isEN = false
        self.contents.removeAll()
        MYGLoading.show()
        MMYGNetwork<MYGResumeApi,MYGResumeModel>.request(target: .personalInfo) { [self] item in
            MYGLoading.hide()
            
            guard let model = item else{return}
            print(model)
            self.doctorResumeModel = model
            self.headerView.model = model.doctor
//            self.contents = model.extModel
            model.extModel.forEach { m in
                if m.modelName != "Internship" {
                    let arr = m.list.filter{$0.is_show == 1 || $0.title.isEmpty == false }
                    let reModel = MYGResumType()
                    reModel.index = m.index
                    reModel.modelName = m.modelName
                    reModel.isShow = m.isShow
                    reModel.list.append(contentsOf: arr)
                    self.contents.append(reModel)
                }
            }
            tableview.reloadData()
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func getCNResumInfo() {
        self.isEN = false
        self.headerView.isEN = false
        isMedia = false
        tableview.reloadData()
    }
    
    func getENResumInfo() {
        self.isEN = true
        isMedia = false
        self.headerView.isEN = true
        tableview.reloadData()
    }
    func getMediaResumInfo(){
        isMedia = true
        self.isEN = false
        self.headerView.isEN = false
        
        let item = MYGResumType()
        item.modelName = "自我介绍"
        let model = MYGResumeAllType()
        model.content = doctorResumeModel.media.content
        model.en_content = doctorResumeModel.media.content
        item.list = [model]
        
        mediaContents = [item]
        
        self.tableview.reloadData()
        
    }
    
    func editResumeInfo(model:MYGResumType,i:Int){
        let type = model.modelName
        var index = 5

        if  type == "Learnings" {
            let vc = MYGResumeEditController()
            vc.model = self.doctorResumeModel
            vc.learnS = [model.list[i]]
            vc.secondStep()
            navigationController?.pushViewController(vc)
            
        } else if (type == "Works"){
            let vc = MYGResumeEditController()
            vc.model = self.doctorResumeModel
            vc.workS = [model.list[i]]
            vc.threeStep()
            navigationController?.pushViewController(vc)
        }else {
            if (type == "GoodAt"){// 专业擅长
                index = 4
            }else if (type == "Honors"){//个人荣誉
                index = 0
            }else if (type == "Clinical"){//临床实验
                index = 5
            }else if (type == "Internship"){//实习经验
                index = 5
            } else if (type == "Publish"){//出版
                index = 2
            }else if (type == "Patent"){//获得专利
                index = 1
            } else if (type == "Custom"){//自定义模块
                index = 5
            }
            let vc = MYGResumeEditEndViewController()
            vc.skills = [model]
            vc.configCell(index)
            navigationController?.pushViewController(vc)
        }
    }
    
    @objc func clickSwitchBtn(_ sender:QMUIButton) {
        sender.isSelected = !sender.isSelected
        let section = sender.tag
        let list = self.contents[section]
        list.isShow = sender.isSelected == true ? 1 : 0
        
    }
    @objc func clickTipBtn(_ sender:QMUIButton) {
        let buttonPosition = sender.convert(CGPoint.zero, to: self.view)
        let tipview = MYGResumeHeaderTipview(frame: CGRect(x: buttonPosition.x - 85, y: buttonPosition.y - 32, width: 187, height: 32))
        tipview.tag = 999
        self.view.addSubview(tipview)
        
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        let v = self.view.viewWithTag(999)
        v?.removeFromSuperview()
    }
}


extension MYGResumeShareVC:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        isMedia ? self.mediaContents.count : self.contents.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let list = isMedia ? self.mediaContents[section] : self.contents[section]
        return list.list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let models = isMedia ? self.mediaContents[indexPath.section] : self.contents[indexPath.section]
        
        if isMedia {
            let cell = tableView.dequeueReusableCell(withClass: MYGMediaTableViewCell.self, for: indexPath)
            cell.isEN = self.isEN
            cell.type = models.modelName
            cell.model = models.list[indexPath.row]
            return cell
        }else {
            if models.modelName == "Learnings" || models.modelName == "Works" {
                let cell = tableView.dequeueReusableCell(withClass: MYGResumeShareCell.self, for: indexPath)
                cell.isEN = self.isEN
                cell.type = models.modelName
                cell.model = models.list[indexPath.row]
                return cell
            }
            else {
                let cell = tableView.dequeueReusableCell(withClass: MYGResumeOtherCell.self, for: indexPath)
                cell.isEN = self.isEN
                cell.type = models.modelName
                cell.model = models.list[indexPath.row]
                return cell
                
            }
        }
        
//        cell.editResumeInfBlock = {[self] in
//            editResumeInfo(model: models,i:indexPath.row)
//        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let models = isMedia ? self.mediaContents[indexPath.section] : self.contents[indexPath.section]
        let model = models.list[indexPath.row]
        
        if models.modelName == "Learnings" || models.modelName == "Works" {
            let str = models.modelName == "Learnings" ? model.experience : model.content
            let size = getStringSize(font: .regular(16), viewSize: CGSize(width: screenWidth - 45, height: CGFLOAT_MAX), str: str)

            return size.height + 78
        }
        
        if models.modelName == "GoodAt" {
            let str = models.modelName == "Learnings" ? model.experience : model.content
            let size = getStringSize(font: .regular(16), viewSize: CGSize(width: screenWidth - 45, height: CGFLOAT_MAX), str: str)

            return size.height + 30
        }
        
        let size = getStringSize(font: .regular(16), viewSize: CGSize(width: screenWidth - 175, height: CGFLOAT_MAX), str: model.title)

        return size.height + 50
    }
   
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: Int(screenWidth), height: 30))
        
        let line = UIView()
        line.backgroundColor = .rgba(73, 117, 236, 1)
        v.addSubview(line)
        
        let tipLab = UILabel()
        tipLab.text = ""
        tipLab.textColor = .rgba(34, 34, 34, 1)
        tipLab.font = .medium(18)
        
        let btn = QMUIButton()
        btn.setImage(UIImage(named: "resume_Off"), for: .normal)
        btn.setImage(UIImage(named: "resume_On"), for: .selected)
        btn.addTarget(self, action: #selector(clickSwitchBtn(_:)), for: .touchUpInside)
        btn.tag = section
        v.addSubview(btn)
       
        v.addSubview(tipLab)
        line.snp.makeConstraints { make in
            make.left.equalTo(17.5)
            make.height.equalTo(15)
            make.width.equalTo(3)
            make.top.equalToSuperview().offset(17.5)
        }
        
        tipLab.snp.makeConstraints { make in
            make.centerY.equalTo(line)
            make.left.equalTo(line.snp.right).offset(13)
            make.height.equalTo(25)
        }
        
        btn.snp.makeConstraints { make in
            make.left.equalTo(tipLab.snp.right).offset(6)
            make.height.equalTo(18)
            make.width.equalTo(26.55)
            make.centerY.equalTo(tipLab)
        }
        if (section == 0){
            let tipBtn = QMUIButton()
            tipBtn.setImage(UIImage(named: "resum_que"), for: .normal)
            tipBtn.addTarget(self, action: #selector(clickTipBtn(_:)), for: .touchUpInside)
            v.addSubview(tipBtn)
            
            tipBtn.snp.makeConstraints { make in
                make.left.equalTo(btn.snp.right).offset(6)
                make.height.equalTo(18)
                make.width.equalTo(26.55)
                make.centerY.equalTo(tipLab)
            }
        }
        
        let list = self.contents[section]
        let type = list.modelName
        btn.isSelected = list.isShow == 1
        if (type == "Learnings"){//教育
            tipLab.text = "教育经历"
        } else if (type == "Works"){//工作
            tipLab.text = "工作经历"
        } else if (type == "GoodAt"){// 专业擅长
            tipLab.text = "专业擅长"
        }else if (type == "Honors"){//个人荣誉
            tipLab.text = "个人荣誉"
        }
        else if (type == "Clinical"){//临床实验
            tipLab.text = "文献"
//        }
//        else if (type == "Internship"){//实习经验
//            tipLab.text = "实习经验"
        } else if (type == "Publish"){//出版
            tipLab.text = "出版"
        }else if (type == "Patent"){//获得专利
            tipLab.text = "获得专利"
        } else if (type == "Custom"){//自定义模块
            tipLab.text = "自定义"
        }else if (type == "自我介绍"){//自定义模块
            tipLab.text = "自我介绍"
        }
            
        return v
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        30
    }
}
